<template>
  <el-dialog
    title="报名备注"
    :visible.sync="visible"
    width="50%"
    class="dialog-remark"
    @close="handleClose"
  >
    <el-form ref="remarkForm" :model="remarkForm" label-width="100px">
      <el-form-item label="历史备注记录">
        <el-table :data="remarkHistory" border>
          <el-table-column prop="time" label="操作时间" width="180" />
          <el-table-column prop="operator" label="操作人" width="120" />
          <el-table-column prop="content" label="备注内容" />
        </el-table>
      </el-form-item>

      <el-form-item label="新增备注">
        <el-input
          type="textarea"
          v-model="remarkForm.remarks"
          rows="4"
          placeholder="请输入备注内容"
        />
      </el-form-item>
    </el-form>

    <div slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitRemark">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getRemarksByParams, listRemarksByParams } from "@/api/training/remarks";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    registrationId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      remarkForm: {
        remarks: "",
        registrationId: ""
      },
      remarkHistory: []
    };
  },
  watch: {
    visible(val) {
      if (val && this.registrationId) {
        this.remarkForm.registrationId = this.registrationId;
        this.loadRemarkData();
      }
    }
  },
  methods: {
    loadRemarkData() {
      const query = {
        foreignId: this.registrationId,
        remarkType: "1"
      };

      // 获取当前备注
      getRemarksByParams(query).then(response => {
        this.remarkForm.remarks = response.data?.remarks || "";
      });

      // 获取历史备注
      listRemarksByParams(query).then(response => {
        if (response.rows && response.rows.length > 0) {
          this.remarkHistory = response.rows.map(item => ({
            time: item.createTime || "",
            operator: item.createBy || "",
            content: item.remarks || item.content || ""
          }));
        } else {
          this.remarkHistory = [
            {
              time: "",
              operator: "系统",
              content: "暂无备注记录"
            }
          ];
        }
      });
    },
    submitRemark() {
      if (!this.remarkForm.remarks.trim()) {
        this.$message.warning("请输入备注内容");
        return;
      }

      // 实际项目中调用备注提交接口
      this.$emit("success", this.remarkForm);
      this.handleClose();
    },
    handleClose() {
      this.$emit("update:visible", false);
      this.$nextTick(() => {
        if (this.$refs.remarkForm) {
          this.$refs.remarkForm.resetFields();
        }
      });
    }
  }
};
</script>
